/*
 * File: SignedRequest.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package data;

import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import faceBook.User;
import foxtrotbravo.QueueAdder;

/**
 * The Class signedRequest.
 */
public class SignedRequest
{

  /**
   * Parses the.
   * 
   * @param signed_request
   *          the signed_request
   * @return the user
   */
  public static User buildUserInfo(String signed_request)
  {
    JSONObject UserInfo = parseAfterDot(signed_request);
    if (UserInfo.has("oauth_token") && UserInfo.has("user_id"))
    {
      try
      {
        long userId = UserInfo.getLong("user_id");
        User user = new User(userId);
        GregorianCalendar twoWeeksFromNow = new GregorianCalendar();
        twoWeeksFromNow.add(Calendar.DAY_OF_MONTH, 14);
        if (user.getExpireTime() == null
            || user.getExpireTime().getTime() < twoWeeksFromNow
                .getTimeInMillis())
        {
          QueueAdder.add("/parseRequest?accessToken="
              + UserInfo.getString("oauth_token") + "&userId=" + userId);
        }
        return user;
      } catch (JSONException e)
      {
        e.printStackTrace();
      }
    }
    return null;
  }

  /**
   * Parses the after dot.
   *
   * @param signed_request the signed_request
   * @return the jSON object
   */
  public static JSONObject parseAfterDot(String signed_request)
  {
    String[] parts = signed_request.split("\\.");
    if (parts.length < 2)
      return new JSONObject();
    return parse(parts[1]);
  }

  /**
   * Parses the signed request.
   * 
   * @param signed_request
   *          the signed_request
   * @return the jSON object
   */
  public static JSONObject parse(String signed_request)
  {
    try
    {
      return new JSONObject(decodeBase64(signed_request));
    } catch (JSONException e)
    {
      e.printStackTrace();
    }
    return new JSONObject();
  }

  /**
   * Decode base64.
   * 
   * @param data
   *          the data
   * @return the string
   */
  public static String decodeBase64(String data)
  {
    Base64 b64 = new Base64();
    byte[] bytes = b64.decode(data);
    String retVal = "";
    for (int i = 0; i < bytes.length; i++)
      retVal += (char) (bytes[i]);
    return retVal;
  }

}
